const fs = require('fs')
const path = require('path')
function setFileName(index, nameLength=4) {
    const indexLength = String(index).length
    const restLength = nameLength - indexLength
    let makeup = ''
    for (let i = 0; i < restLength; i++) {
        makeup += '0'
    }
    return `${makeup}${index}`
}
// 先判断有无目标文件夹 ，有继续，没有创建
function checkDir(downloadPath){
  return new Promise((res, rej) => {
    fs.access(downloadPath, fs.constants.F_OK, (err) => {
      if (err) {
          fs.mkdir(downloadPath, (err) => {
              if (err) {
                  console.log('创建失败', err)
            rej({ success: false })
          } else {
            res({ success: true, dirPath: downloadPath })
          }
        })
      }
      else {
        res({ success: true, dirPath: downloadPath })
      }
    })
  })
}

function clearDir(dir){
  return new Promise((res)=>{

    fs.readdir(dir,(err,files)=>{
      if(err){
        res({ success: false, err })

      }else{
        if (files.length){
          files.forEach(file=>{
            // 青空文件夹内容
            fs.unlink(path.resolve(dir,file),(err)=>{
              if(err){
                res({success:false,err})
              }else{
                res({success:true})
              }
            })
          })
        }else{
            res({success:true})
        }
      }
    })
  })
}

module.exports ={
  checkDir,
  setFileName,
  clearDir
  
}